import React = require("react");
import { PageProps } from "maishu-chitu-react";
import { Application } from "maishu-admin";

interface Props extends PageProps {
    data: {
        target: string
    }
}

export default class OuterPage extends React.Component<Props> {
    private element: HTMLElement;

    updateSize() {
        this.element.style.height = `${window.innerHeight - 100}px`;
    }
    formatString(s: string, args: string[]) {
        // var s = arguments[0];
        for (var i = 0; i < args.length; i++) {
            var reg = new RegExp("\\{" + i + "\\}", "gm");
            s = s.replace(reg, args[i]);
        }
        return s;
    }
    componentDidMount() {
        this.updateSize();
        window.addEventListener("resize", () => {
            this.updateSize();
        })
    }
    render() {
        let url = this.props.data.target;
        if (url) {
            url = decodeURIComponent(url);
            let app = this.props.app as Application;
            console.assert(app.loginInfo.value != null);
            url = this.formatString(url, [app.loginInfo.value.userId]);
        }

        let anchor = document.createElement("a");
        anchor.href = url;

        if (anchor.hash) {
            let routeUrl = anchor.hash.substring(1);
            let r = this.props.app.parseUrl(routeUrl);
            r.values["container"] = "blank";
            routeUrl = this.props.app.createUrl(r.pageName, r.values);
            url = `${anchor.protocol}//${anchor.host}${anchor.pathname}#${routeUrl}`;
        }


        return <iframe style={{ width: "100%", border: "none" }}
            ref={e => this.element = e || this.element}
            src={url}>

        </iframe>
    }
}